import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

export type Language = 'zh-CN' | 'en-US';

export interface I18nData {
  [key: string]: any;
}

@Injectable({
  providedIn: 'root'
})
export class I18nService {
  private currentLang = new BehaviorSubject<Language>('zh-CN');
  public currentLang$ = this.currentLang.asObservable();

  private translations: { [key in Language]: I18nData } = {
    'zh-CN': {
      app: {
        title: '电商后台管理系统',
        language: '语言'
      },
      product: {
        title: '商品管理',
        list: '商品列表',
        add: '添加商品',
        edit: '编辑商品',
        delete: '删除商品',
        deleteConfirm: '确定要删除该商品吗？',
        id: '商品ID',
        name: '商品名称',
        category: '分类',
        price: '价格',
        stock: '库存',
        description: '描述',
        status: '状态',
        actions: '操作',
        active: '上架',
        inactive: '下架',
        search: '搜索商品',
        total: '共 {0} 条',
        tableHint: '💡 提示：表格可以左右滚动查看所有列，操作按钮在最右侧'
      },
      form: {
        required: '此字段为必填项',
        submit: '提交',
        cancel: '取消',
        save: '保存',
        reset: '重置'
      },
      message: {
        addSuccess: '添加成功',
        editSuccess: '编辑成功',
        deleteSuccess: '删除成功',
        operationFailed: '操作失败'
      },
      common: {
        confirm: '确认',
        cancel: '取消',
        ok: '确定',
        yes: '是',
        no: '否'
      }
    },
    'en-US': {
      app: {
        title: 'E-commerce Admin System',
        language: 'Language'
      },
      product: {
        title: 'Product Management',
        list: 'Product List',
        add: 'Add Product',
        edit: 'Edit Product',
        delete: 'Delete Product',
        deleteConfirm: 'Are you sure you want to delete this product?',
        id: 'Product ID',
        name: 'Product Name',
        category: 'Category',
        price: 'Price',
        stock: 'Stock',
        description: 'Description',
        status: 'Status',
        actions: 'Actions',
        active: 'Active',
        inactive: 'Inactive',
        search: 'Search Product',
        total: 'Total {0} items',
        tableHint: '💡 Tip: Scroll the table horizontally to view all columns, action buttons are on the right'
      },
      form: {
        required: 'This field is required',
        submit: 'Submit',
        cancel: 'Cancel',
        save: 'Save',
        reset: 'Reset'
      },
      message: {
        addSuccess: 'Added successfully',
        editSuccess: 'Edited successfully',
        deleteSuccess: 'Deleted successfully',
        operationFailed: 'Operation failed'
      },
      common: {
        confirm: 'Confirm',
        cancel: 'Cancel',
        ok: 'OK',
        yes: 'Yes',
        no: 'No'
      }
    }
  };

  constructor() {
    // Check if we're in browser environment
    if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {
      const savedLang = localStorage.getItem('language') as Language;
      if (savedLang && (savedLang === 'zh-CN' || savedLang === 'en-US')) {
        this.currentLang.next(savedLang);
      }
    }
  }

  setLanguage(lang: Language): void {
    this.currentLang.next(lang);
    if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {
      localStorage.setItem('language', lang);
    }
  }

  getCurrentLanguage(): Language {
    return this.currentLang.value;
  }

  translate(key: string, params?: any[]): string {
    const keys = key.split('.');
    let value: any = this.translations[this.currentLang.value];
    
    for (const k of keys) {
      if (value && typeof value === 'object') {
        value = value[k];
      } else {
        return key;
      }
    }

    if (typeof value === 'string' && params) {
      params.forEach((param, index) => {
        value = value.replace(`{${index}}`, param);
      });
    }

    return value || key;
  }

  t(key: string, params?: any[]): string {
    return this.translate(key, params);
  }
}
